package ru.evga.billboard.graph;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


public class DocumentContainer
{
    private static final int BUF_SIZE = 1024;
    public static final String DOCUMENT_EXSTENSION = ".billboard";
    private String filePath;
    public static final String SETTINGS_ENTRY = "settings";
    public static final String FRAMES_ENTRY = "frames";
    public static final String BUS_ENTRY = "bus";
    public static final String IMAGE_ENTRY = "image";

    public DocumentContainer(String p)
    {
        this.filePath = p;
        if (!filePath.endsWith(DOCUMENT_EXSTENSION))
        {
            this.filePath = this.filePath + DOCUMENT_EXSTENSION;
        }
    }

    public void save(InputStream preferenceStream, InputStream frames, InputStream bus, InputStream img)
        throws IOException
    {
        ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(filePath));
        writeEntry(preferenceStream, outStream, SETTINGS_ENTRY);
        writeEntry(frames, outStream, FRAMES_ENTRY);
        writeEntry(bus, outStream, BUS_ENTRY);
        writeEntry(img, outStream, IMAGE_ENTRY);
        outStream.closeEntry();
        outStream.close();
    }

    private void writeEntry(InputStream preferenceStream, ZipOutputStream outStream,
        String entryName)
        throws IOException
    {
        if (preferenceStream == null)
        {
            return;
        }
        outStream.putNextEntry(new ZipEntry(entryName));
        byte [] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = preferenceStream.read(buffer)) > 0)
        {
            outStream.write(buffer, 0, bytesRead);
        }
    }

    public byte [] getData(String entryName) throws IOException
    {
        ZipFile zf = new ZipFile(filePath);
        ZipEntry entry = zf.getEntry(entryName);
        if (entry != null)
        {
            InputStream is = zf.getInputStream(entry);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte [] buf = new byte[BUF_SIZE];
            int len;
            while ((len = is.read(buf, 0, BUF_SIZE)) != -1)
            {
                buffer.write(buf, 0, len);
            }
            return buffer.toByteArray();
        }
        return null;
    }
}
